<template>
  <el-cascader
    v-model="departments"
    :props="cascaderProps"
    class="departmentCascader"
    ref="DepartmentCascader"
    :options="departmentList"
  ></el-cascader>
</template>

<script>
export default {
  name: 'DepartmentCascader',
  props: {},
  components: {},
  data() {
    return {
      // 级联选择器配置项
      cascaderProps: {
        expandTrigger: 'click',
        value: 'id',
        label: 'department_name',
        children: 'children',
        lazy: true,
        // 懒加载
        lazyLoad: this.LoadDepartmentChildren
      },
      // 部门列表
      departmentList: [],
      // 部门
      departments: '',
      selectedNode: {}
    }
  },
  computed: {},
  watch: {
    departments: {
      deep: true,
      immediate: true,
      handler(val, oldval) {
        let departmentId = val[val.length - 1]
        this.$store.commit('user/GETDEPARTMENTID', departmentId)
      }
    }
  },
  created() {},
  mounted() {
    this.getDepartmentData()
  },
  methods: {
    // 子节点部门获取
    async LoadDepartmentChildren(node, resolve) {
      console.log(node)
      const children = await this.$API.department.getDepartmentByAncestor(
        node.value
      )
      if (children && children.status == 200) {
        if (Array.isArray(children.data) && children.data.length == 0) {
          this.$refs.DepartmentCascader.visible = false
          //   console.log(this.departmentId[this.departmentId.length-1])
          // this.$store.state.user.departmentId=this.departmentId[-1]
        }
        resolve(children.data)
      } else {
        resolve([])
      }
    },
    // 获取部门数据
    async getDepartmentData() {
      const res = await this.$API.department.getRootDepartment()
      // console.log(res)
      if (res.status == 200) {
        this.departmentList = res.data
      }
    }
  }
}
</script>

<style scoped>
.departmentCascader {
  width: 100%;
}
.departmentCascader >>> .el-input__inner {
  background-color: #f4f5f5;
}
.departmentCascader >>> .el-input__prefix {
  position: absolute;
  top: 5px;
}
.departmentCascader >>> .el-input__inner::placeholder {
  color: #8d8f91;
}
</style>
